package Servlets;

import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import ServerDB.User;
import ServerDB.UserManager;


public class RegisterServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final String NEW_LINE=System.getProperty("line.separator").toString();
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		boolean haveError=false;
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		out.println("<HTML>");
		out.println("<HEAD>");
		System.out.println("Check Login");
		String userName=request.getParameter("userNameTextBox").toString();
		String password=request.getParameter("passwordTextBox").toString();
		String rePassword=request.getParameter("RepasswordTextBox").toString();
		String email=request.getParameter("emailTextBox").toString();
		System.out.println("bla1");
		File file=new File("C:\\ourDropBox\\hibernate.cfg.xml");
		SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
		Session session=sessionFactory.openSession();
		String strQuery=" SELECT * FROM tbl_users WHERE USER_NAME = :userNameQry";
		Query query=session.createSQLQuery(strQuery);
		query.setParameter("userNameQry", userName);
		
		@SuppressWarnings("unchecked")
		List<User> listUsers=query.list();
		Iterator<User> itUser=listUsers.iterator();
		
		if(itUser.hasNext())//Response The user name is in DataBase
		{
			haveError=true;
			System.out.println("I am exist ! Fuck YOU!");
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("error user exist", "error user exist");
			
		}		
		if(!rePassword.equals(password))
		{
			haveError=true;
			System.out.println("No same Password");
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("error password", "password and re-password different");
		}
		//TODO: check Email!
		//TODO: check Password length
		if(!haveError)
		{
			
			//User register is Ok 
			User user= new User();
			user.setUserName(userName);
			user.setPassword(password);
			user.setEmail(email);
			System.out.println("Adding DB the user "+ userName);
			UserManager userManager=new UserManager(session);
			userManager.saveUser(user);
			session.flush();
		}
			
		
		if(haveError)
		{
			out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=register.jsp'>");
		}
		else
		{
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("No error", "No error");
			httpSession.setAttribute("Login", userName);

			out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=afterLogin.jsp'>");
		}
		out.println("</HEAD>");
		out.println("<BODY>");
		out.println("</BODY>");
		out.println("</HTML>");
		out.close();
				
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		ArrayList<String> errorList=new ArrayList<String>();
		boolean haveError=false;
		System.out.println("Check Login");
		String userName=request.getParameter("userName").toString();
		String password=request.getParameter("password").toString();
		String rePassword=request.getParameter("rePassword").toString();
		String email=request.getParameter("email").toString();
		System.out.println("bla1");
		File file=new File("C:\\ourDropBox\\hibernate.cfg.xml");
		SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
		Session session=sessionFactory.openSession();
		String strQuery=" SELECT * FROM tbl_users WHERE USER_NAME = :userNameQry";
		Query query=session.createSQLQuery(strQuery);
		query.setParameter("userNameQry", userName);
		
		@SuppressWarnings("unchecked")
		List<User> listUsers=query.list();
		Iterator<User> itUser=listUsers.iterator();
		if(userName=="" || password=="" || rePassword=="" || email=="")
		{
			haveError=true;
			errorList.add("You have to fill all the fields"+NEW_LINE);
		}
		if(itUser.hasNext())//Response The user name is in DataBase
		{
			haveError=true;
			errorList.add("Username already exist"+NEW_LINE);
			
			
		}		
		if(!rePassword.equals(password))
		{
			haveError=true;
			errorList.add("Password incorrect"+NEW_LINE);
		}
		//TODO: check Email!
		//TODO: check Password length
		if(!haveError)
		{
		/*	
			//User register is Ok 
			User user= new User();
			user.setUserName(userName);
			user.setPassword(password);
			user.setEmail(email);
			System.out.println("Adding DB the user "+ userName);
			UserManager userManager=new UserManager(session);
			userManager.saveUser(user);
			session.flush();
		*/}
			
		
		ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());
		out.writeObject(errorList);
		out.close();
	
	}	
}
